package com.example.duihua.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Value("${netty.websocket.path}")
    private String websocketPath;

    @Autowired
    private WebSocketHandler webSocketHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        
        // HTTP协议解码器
        pipeline.addLast(new HttpServerCodec());
        // 将多个消息转换为单一的FullHttpRequest或FullHttpResponse
        pipeline.addLast(new HttpObjectAggregator(65536));
        // 支持异步发送大的码流
        pipeline.addLast(new ChunkedWriteHandler());
        // WebSocket协议处理器，处理握手、控制帧等
        pipeline.addLast(new WebSocketServerProtocolHandler(websocketPath, null, true));
        // 自定义的WebSocket处理器
        pipeline.addLast(webSocketHandler);
    }
}